const express = require("express");
const multer = require("multer");
const fs = require("fs");
const path = require("path");
const app = express();
const os = require("os");
const qrcode = require("qrcode");
const chalk = require("chalk");

function getIPAddress() {
  const interfaces = os.networkInterfaces();
  for (const devName in interfaces) {
    const iface = interfaces[devName];
    for (let i = 0; i < iface.length; i++) {
      const alias = iface[i];
      if (
        alias.family === "IPv4" &&
        alias.address !== "127.0.0.1" &&
        !alias.internal
      ) {
        return alias.address;
      }
    }
  }
  return null;
}

const storage = multer.diskStorage({
  destination(req, file, cb) {
    cb(null, "uploads/");
  },
  filename(req, file, cb) {
    cb(null, file.originalname);
  },
});

const upload = multer({ storage });

app.post("/upload", async (req, res) => {
  const fileName = decodeURIComponent(req.headers["x-file-name"]);
  const fileSize = parseInt(req.headers["x-file-size"], 10);
  const startByte = parseInt(req.headers["x-start-byte"], 10);
  const uploadDir = path.join(os.homedir(), "Documents", `uploads`);

  // 确保目录存在
  if (!fs.existsSync(uploadDir)) {
    fs.mkdirSync(uploadDir, { recursive: true });
  }

  const filePath = path.join(uploadDir, fileName);

  if (!fs.existsSync(filePath)) {
    fs.writeFileSync(filePath, "");
  }

  const fileStream = fs.createWriteStream(filePath, {
    flags: "a",
    start: startByte,
  });
  req.pipe(fileStream);

  req.on("data", (chunk) => {
    // console.log(chunk.length);
    return chunk;
  });

  req.on("end", () => {
    if (fs.statSync(filePath).size === fileSize) {
      res.send("Upload completed.");
    } else {
      res.status(500).send("Upload failed.");
    }
  });
});

app.get("/", (req, res) => {
  // 返回 HTML 页面
  fs.readFile(path.join(__dirname, "index.html"), (err, data) => {
    if (err) {
      res.writeHead(500, { "Content-Type": "text/plain" });
      res.end("Internal Server Error");
    } else {
      res.writeHead(200, { "Content-Type": "text/html" });
      res.end(data);
    }
  });
});

app.get("/progress/:fileName", (req, res) => {
  const fileName = req.params.fileName;
  const filePath = `uploads/${fileName}`;
  if (fs.existsSync(filePath)) {
    res.send(fs.statSync(filePath).size.toString());
  } else {
    res.send("0");
  }
});

app.listen(3000, () => {
  console.log(`http://${getIPAddress()}:3000`);
});

const ipAddress = getIPAddress();
const url = `http://${ipAddress}:3000`;

console.log(chalk.bgYellow.red.bold(`\n${url}\n`));

qrcode.toString(url, { type: "terminal" }, function (err, QRCode) {
  if (err) {
    console.error(err);
    return;
  }
  console.log(QRCode);
});
